import wepy from 'wepy'

export default class Home extends wepy.mixin {
  data = {
    queryData:{
      query:'',
      cid:'',
      pagenum:1,
      pagesize:10
    },
    // 商品列表
    goods:[],
    // 总条数
    total:0,
    // 是否正在请求
    isloading:false,
    // 是否显示数据已达上限
    isover:true
  }

  methods = {
    goDetail(id){
      wepy.navigateTo({
        url:`/pages/goods_detail/main?goods_id=${id}`
      })
    }
  }
  async getGoodsList(fn){
    this.isloading=true
   const {data:res}= await wepy.get('/goods/search',this.queryData)
   if(res.meta.status!=200) return wepy.baseToast()
   this.goods=[...this.goods,...res.message.goods]
   this.total=res.message.total
   this.isloading=false
   fn&&fn()
   this.$apply()
   return true
  }
  onLoad(options){
   this.queryData.query=options.query?options.query:''
   this.queryData.cid=options.cid?options.cid:''
   this.getGoodsList()
  }
  onReachBottom(){
    // 如果正在加载下一页数据,则阻止再次发送请求
    if(this.isloading)return
    if(this.pagenum*this.pagesize>this.total){
      this.isover=false
    }
    this.queryData.pagenum++;
    this.getGoodsList()
  }
  // 监听下拉刷新
  onPullDownRefresh(){
   
    this.queryData.pagenum=1
    this.goods=[]
    this.isover=true
    this.getGoodsList(()=>{
      wepy.stopPullDownRefresh()
    })
  }
}